Constructors and destructors in C#

Constructors are special methods that are used immediately when using a class that the manufacturer can never return anything, that is why you do not need to define a return type for it. A general method is defined:


public string Describe()

A constructor can be defined like this:


public Car()

In our example for this section, we have a car category, which has a constructor, which takes the string as a logic Of course, a constructor can be overloaded too, which means that we have many constructors with the same name You can create different parameters, but here are an example:


public Car()
{

}

public Car(string color)
{
    this.color = color;
}

A constructor can call another constructor, which can come in handy in several situations. Here is an example:


public Car()
{
    Console.WriteLine("Constructor with no parameters called!");
}

public Car(string color) : this()
{
    this.color = color;
    Console.WriteLine("Constructor with color parameter called!");
}

If you run this code, you will see that the constructor with a parameter is not called first. This can be used in the default constructor for different objects for class, which can be told from other class constructors. If constructors take the parameters you want to call, then you can do that too. Here is a simple example:


public Car(string color) : this()
{
    this.color = color;
    Console.WriteLine("Constructor with color parameter called!");
}

public Car(string param1, string param2) : this(param1)
{

}

If you call the constructor which takes 2 parameters, the first parameter will be used to invoke the constructor that takes 1 parameter.

Destructors

Since C # garbage is gathered, given that the structure will free those items you no longer use, there may be times where you need to make manual confirmation. A destroyer, once the object is used, an object is used, it can be used to clean the resources used by the object. Destructors seem not very much like other methods in C #. Here is an example of a disaster for our car class:


~Car() 
{
    Console.WriteLine("Out..");
}

Once the object is collected by the garbage collector, this method is called.